package utils;


import android.content.Context;
import android.content.SharedPreferences;

public class PreferenceUtils {

    private SharedPreferences preference;
    private static PreferenceUtils instance = null; //唯一的实例
    private final String IS_LOGIN = "IS_LOGIN";  //变量的 Key
    private final String USER_NAME = "USER_NAME";

    private PreferenceUtils(Context ctx) {
        preference = ctx.getSharedPreferences("local", Context.MODE_PRIVATE);
    }

    public static PreferenceUtils getInstance(Context ctx) {
        if (instance != null) {
            return instance;
        }
        instance = new PreferenceUtils(ctx); //实例化只会执行一次
        return instance;
    }

    public boolean readLoginStatus() {
        return preference.getBoolean(IS_LOGIN, false);
    }

    public String readUserName() {
        return preference.getString(USER_NAME, "");
    }

    public void saveLoginStatus(boolean isLogin, String userName) {
        preference.edit().putBoolean(IS_LOGIN, isLogin).apply();
        preference.edit().putString(USER_NAME, userName).apply();
    }
    public void savePassword(String userName, String pwd) {
        //TODO pwd换成密文
        preference.edit().putString(userName,  pwd).apply();
    }

    public String getPassword(String userName) {
        return preference.getString(userName,  "");
    }

    public boolean isUserExist(String userName) {
        String pwd = getPassword(userName);
        return pwd.length() > 0;
    }
}


